/**
 * @Author yang
 * @Description //TODO
 * @Date 2021/6/11
 * @Time 9:59
 **/
package files

import (
	"bufio"
	"errors"
	"github.com/lunny/log"
	"io/ioutil"
	"os"
	"strings"
)

// 文件写入工具
func FileAppender(filePath string) (writerFunc func(content []byte, isClose bool) error, err error) {
	file, err := createFile(filePath)
	if err != nil {
		return nil, err
	}
	write := bufio.NewWriter(file)
	writerFunc = func(content []byte, isClose bool) error {
		if isClose {
			defer file.Close()
		}
		_, err := write.Write(content)
		if err != nil {
			return err
		}
		//Flush将缓存的文件真正写入到文件中
		err = write.Flush()
		if err != nil {
			return err
		}
		return nil
	}
	return writerFunc, nil
}

func FileWrite(filepath string, content []byte) error {
	err := checkDir(filepath)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(filepath, content, 0666)
}

// 创建文件
func createFile(filePath string) (*os.File, error) {
	err := checkDir(filePath)
	if err != nil {
		return nil, err
	}

	return os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	//及时关闭file句柄
	//defer file.Close()
}

// 查看路径是否存在
func checkDir(filePath string) error {
	if strings.TrimSpace(filePath) == "" {
		return errors.New("路径不能为空！")
	}
	pathSeprator := ""
	if strings.Contains(filePath, "/") {
		pathSeprator = "/"
	} else if strings.Contains(filePath, "\\") {
		pathSeprator = "\\"
	}
	if pathSeprator == "" {
		log.Debugf("%v--没有需要创建的文件夹", filePath)
		return nil
	}

	index := strings.LastIndex(filePath, pathSeprator)
	dir := filePath[:index+1]
	//filename := filePath[index+1:]

	err := os.MkdirAll(dir, 0666)
	if err != nil {
		return err
	}
	return nil
}
